/**
 * @description 连接 redis 的方法 get set
 * @author Vennasia
 */

const redis = require('redis');
const REDIS_CONF = config.redis;

// 创建客户端
const redisClient = redis.createClient(REDIS_CONF.port, REDIS_CONF.host);

redisClient.on('error', err => {
  console.log('redis error', err)
});

/**
 * redis set
 * @param {string} key
 * @param {string} val
 * @param {number} timeout 过期时间,单位为秒
 */
function set(key, val, timeout = 60 * 60) {
  return new Promise((resolve, reject) => {
    if (typeof val === 'object') {
      val = JSON.stringify(val)
    }
    redisClient.set(key, val, (err, res) => {
      if (err) return reject(err);
      redisClient.expire(key, timeout, (err, res) => {
        if (err) return reject(err);
        // console.log('err:', err); // null
        // console.log('res:', res); // 1 (貌似是key存在的时候就为1,不存在为0)
        resolve();
      })
    });
  });
}

/**
 * redis get
 * @param {string} key 键
 */
function get(key) {
  return new Promise((resolve, reject) => {
    redisClient.get(key, (err, val) => {
      if (err) {
        reject(err);
        return
      }
      if (val == null) {
        resolve(null);
        return
      }
      try {
        resolve( // 尝试将json变成对象
          JSON.parse(val)
        )
      } catch (e) {
        resolve(val)
      }
    })
  })
}

/**
 * redis del
 * @param {string} key
 * @return {Promise<unknown>}
 */
function del(key) {
  return new Promise((resolve, reject) => {
    redisClient.expire(key, 0, (err, res) => {
      if (err) return reject(err);
      resolve();
    })
  });
}

module.exports = {
  set
  , get
  , del
};
